import React from "react";
import { Button, Checkbox, Form, Input } from "antd";
import { getlogin } from "../../api/index";
import { useNavigate } from "react-router-dom";

// 定义表单数据类型
interface LoginFormValues {
  username: string;
  password: string;
  remember: boolean;
}

// 定义后端返回数据类型
interface LoginResponse {
  data: {
    code: number;
    message: string;
    data: {
      accessToken: string;
      userInfo: any;
    };
  };
}

function Login() {
  let navigate = useNavigate();

  // 点击登录
  const onFinish = async (values: LoginFormValues) => {
    console.log("Success:", values);
    // 将输入的账号密码存储到对象
    const data = {
      username: values.username,
      password: values.password,
    };

    try {
      // 发送数据到后端
      const res: LoginResponse = await getlogin(data);
      console.log(res);

      // 当 code 等于 10000 时
      if (res.data.code === 10000) {
        // 本地存储
        localStorage.setItem("token", res.data.data.accessToken);
        localStorage.setItem(
          "userInfo",
          JSON.stringify(res.data.data.userInfo)
        );
        alert(res.data.message);
        // 跳转首页
        navigate("/home");
      } else {
        // 处理其他状态码
        alert(res.data.message);
      }
    } catch (error) {
      // 处理网络请求错误
      console.error("登录请求出错:", error);
      alert("登录请求出错，请稍后重试");
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    console.log("Failed:", errorInfo);
  };

  return (
    <div>
      <Form
        name="basic"
        labelCol={{ span: 8 }}
        wrapperCol={{ span: 16 }}
        style={{ maxWidth: 600 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off"
      >
        <Form.Item
          label="Username"
          name="username"
          rules={[{ required: true, message: "Please input your username!" }]}
        >
          <Input />
        </Form.Item>

        <Form.Item
          label="Password"
          name="password"
          rules={[{ required: true, message: "Please input your password!" }]}
        >
          <Input.Password />
        </Form.Item>

        <Form.Item name="remember" valuePropName="checked" label={null}>
          <Checkbox>Remember me</Checkbox>
        </Form.Item>

        <Form.Item label={null}>
          <Button type="primary" htmlType="submit">
            登
          </Button>
        </Form.Item>
      </Form>
    </div>
  );
}

export default Login;
